package com.chenjl.trace.transport;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.ByteArrayDeserializer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chenjl.trace.Constant;
/**
 * Kafka消息消费者 + protobuf压缩
 * 2018-9-25 18:50:42
 * @author chenjinlong
 */
public class KafkaByteMessageConsumer {
	private static final Logger log = LoggerFactory.getLogger(KafkaByteMessageConsumer.class);
	
	public static void main(String[] args) throws InterruptedException {
		
		Properties props = new Properties();
		props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,Constant.BROKER_URL);
		props.put(ConsumerConfig.GROUP_ID_CONFIG,"test consumer");
		props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,"true");
		props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");
		props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "30000");
		props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class);
		props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,ByteArrayDeserializer.class);
		
		Consumer<String,byte[]> consumer = new KafkaConsumer<String,byte[]>(props);
		consumer.subscribe(Arrays.asList(Constant.TOPIC_NAME_PROTOBUF));
		log.info("consumer poll begin");
		
		for(int i=1;i<=20;i++) {
			ConsumerRecords<String,byte[]> messages = consumer.poll(Duration.ofSeconds(5));
			log.info("consumer poll end , message count : {}",messages.count());
			
			for(ConsumerRecord<String,byte[]> message : messages) {
				String strValue = new String(message.value());
				log.info("consumer message , key : {}, value : {} , offset : {}",message.key(),strValue,message.offset());
			}
			
			Thread.sleep(1000);
		}
		
		log.info("consumer end");
		consumer.commitSync();
		consumer.close();
	}
}